import {defineStore} from 'pinia'
import userApi,{type userInfo} from '@/api/user'
import type { formDataModel } from "@/api/register";
import {setToken,removeToken, getToken} from '@/utils/token-utils'

interface stateModel {
  token:string,
  userInfo:userInfo
}

const initUserInfo = ( )=> ({
  nickName:'',
  name:''
})

const useUserStore = defineStore('userStore',{

  state():stateModel {
    return {
      token:getToken() || '',
      userInfo:initUserInfo()
    }
  },

  actions:{
    async login (params:formDataModel) {
      try {
        const res = await userApi.login({
          phone:params.phone,
          password : params.password
        })
        this.token = res.token
        setToken(res.token)
        this.getUserInfo()
      } catch (error) {
        console.log(error);
        Promise.reject(error)
      }
    },
  
    async getUserInfo(){
      try {
        const res = await userApi.getUserInfo()
        this.userInfo = res
      } catch (error) {
        console.log(error);
        Promise.reject(error)
      }
    },

    async logout(){
      try {
        await userApi.logout()
      } catch (error) {
        console.log(error);
        Promise.reject(error)
      }finally{
        this.token = '',
        this.userInfo = initUserInfo()
        removeToken()
      }
    }
  },

  

})

export default useUserStore